import struct
import socket

packer = struct.Struct('i 64s i i')
HOST, PORT = "localhost", 10013

def connsvr():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))
    # send ready signal
    pOut = packer.pack(2, '', 0, 0)
    sock.sendall(pOut)
    # set name
    pOut = packer.pack(1, 'soup 1234', 0, 0)
    sock.sendall(pOut)
    return sock

def play(total_rnd=100):
    try:
        sock = connsvr()
        
        points = 0
        bet = 10
        rnd = 0
        won = 0
        lost = 0
        while rnd < total_rnd:
            reply = sock.recv(packer.size)
            if reply == '':
                continue
            cmd, msg, v1, v2 = packer.unpack(reply)
            
            if cmd == 4:
                pOut = packer.pack(5, '', bet, 0)
                sock.sendall(pOut)
            elif cmd == 8:
                # got a new card
                points += v2
                print 'Got card %d. Total %d.' % (v2, points)
            elif cmd == 6:
                if points < 15:
                    pOut = packer.pack(7, '', 1, 0)
                else:
                    pOut = packer.pack(7, '', 0, 0)
                sock.sendall(pOut)
            elif cmd == 9:
                print '%s for %d.' % (msg, v1)
                print '==============================='
                sock.close()
                
                if msg.find('won') > 0:
                    won += 1
                else:
                    lost += 1
                
                rnd += 1
                points = 0
                sock = connsvr()
            elif cmd == 10:
                print msg
        print 'Won %d, Lost %d.' % (won, lost)
    except Exception as e:
        print e
    finally:
        sock.close()

if __name__ == '__main__':
    import sys
    try:
        rnd = int(sys.argv[1])
    except:
        play()
    else:
        play(rnd)

